package com.zmn.oms.business.impl.master;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MathUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.cube.common.dio.board.BoardConfigDIO;
import com.zmn.cube.common.dio.board.query.OrderBoardQueryDIO;
import com.zmn.cube.common.dto.board.BoardResultDO;
import com.zmn.cube.common.dto.board.ReportDTO;
import com.zmn.cube.common.dto.measure.MeasureResultDO;
import com.zmn.cube.dubbo.dto.BoardCustomDIO;
import com.zmn.cube.dubbo.interfaces.board.BoardRemoteService;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.interfaces.master.MasterQuotationBRateService;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.model.vo.master.QuotationRateRankingVO;
import com.zmn.oms.model.vo.master.QuotationRateVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：SongWeidong
 * @date ：2021/3/2 11:51
 * @description：计价器使用率
 */
@Slf4j
@Service
public class MasterQuotationBRateServiceImpl implements MasterQuotationBRateService {

    private Logger logger = LoggerFactory.getLogger(MasterQuotationBRateServiceImpl.class);

    @DubboReference(version = com.zmn.cube.dubbo.utils.constant.DubboConsts.INTERFACE_VERSION, check = false, timeout = 99999999)
    private BoardRemoteService boardRemoteService;

    @Autowired
    private RedisManager redisManager;

    /**
     * 查询使用率列表
     * @param orgThrId
     * @return
     */
    @Override
    public List<QuotationRateVO> queryQuotation(Integer orgThrId) {

        String redisKey;
        if (Objects.nonNull(orgThrId)) {
            redisKey = String.format(RedisKeyConsts.COMPANY_MASTER_QUOTATION_RATE_KEY, orgThrId);
        } else {
            redisKey = RedisKeyConsts.ALL_MASTER_QUOTATION_RATE_KEY;
        }
        return JSON.parseArray(redisManager.get(redisKey), QuotationRateVO.class);
    }


    @Override
    public void saveCompanyQuotationRate(Integer orgThrId) {

        // 查询使用率数据
        List<QuotationRateVO> voList = this.queryQuotationRate(orgThrId);
        // 将结果缓存
        String redisKey = String.format(RedisKeyConsts.COMPANY_MASTER_QUOTATION_RATE_KEY, orgThrId);
        redisManager.set(redisKey, JSON.toJSONString(voList));
    }

    @Override
    public void saveAllQuotationRate() {
        // 查询使用率数据
        List<QuotationRateVO> voList = this.queryQuotationRate(null);
        // 将结果缓存
        String redisKey = RedisKeyConsts.ALL_MASTER_QUOTATION_RATE_KEY;
        redisManager.set(redisKey, JSON.toJSONString(voList));
    }

    @Override
    public List<QuotationRateVO> queryQuotationRate(Integer orgThrId) {

        BoardCustomDIO<OrderBoardQueryDIO> queryDIO = new BoardCustomDIO<>();
        queryDIO.setDatasetId(1000);

        BoardConfigDIO boardConfigDIO = new BoardConfigDIO();
        boardConfigDIO.setDayLimit(1000);
        boardConfigDIO.setDebug(true);
        boardConfigDIO.setDimensionY("sp_company_id,engineer_visit_id,serv_group_id");
        // 设置查询维度和查询指标 计价器有效使用率指标id 800155
        boardConfigDIO.setMeasureIds(Lists.newArrayList(800155));
        queryDIO.setBoardConfigDIO(boardConfigDIO);

        // 排名数据获取的当月数据（月初-昨日）
        Date startDate = DateUtil.parse(DateUtil.getMonthFirstDay(DateUtil.getNow()), DateUtil.FORMAT_DEFAULT);
        String timeRange = String.format("%s-%s", DateUtil.toString(startDate, DateUtil.FORMAT_DATE3),
                DateUtil.toString(DateUtil.addDays(DateUtil.getDateStart(DateUtil.getNow()), -1),DateUtil.FORMAT_DATE3));
        // timeRange = String.format("%s-%s", "2021/05/01", "2021/12/01");
        OrderBoardQueryDIO orderBoardQueryDIO = new OrderBoardQueryDIO();
        orderBoardQueryDIO.setTimeType("distribute_time");
        orderBoardQueryDIO.setTimeRange(timeRange);
        orderBoardQueryDIO.setPlat(GlobalConsts.PLAT_MARK_ZMN);
        if (Objects.nonNull(orgThrId)) {
          orderBoardQueryDIO.setOrgThrId(orgThrId);
        }
        queryDIO.setBoardQueryDIO(orderBoardQueryDIO);

        //logger.debug("查询入参：boardCustomDIO：{}", JSONObject.toJSONString(queryDIO));
        ReportDTO<BoardResultDO<Double>> customReport = boardRemoteService.getCustomReport(queryDIO);
//        logger.debug("查询出参：boardCustomDIO：{}", JSONObject.toJSONString(customReport));
        BoardResultDO<Double> boardResultDO = customReport.getData();
        List<QuotationRateVO> quotationRateList = Lists.newArrayList();
        if (boardResultDO == null || boardResultDO.getItemCells() == null || boardResultDO.getItemCells().size() == 0) {
            return quotationRateList;
        }

        boardResultDO.getItemCells().rowMap().forEach((k, v)->{
            // logger.info("rowMap-item->{}, {}", k, JSON.toJSONString(v));
            MeasureResultDO<Double> doubleMeasureResultDO = v.get("x-800155");
            if (doubleMeasureResultDO == null) {
                return;
            }

            String[] strArr = k.split("#");
            QuotationRateVO rateVO = new QuotationRateVO();
            rateVO.setManageCompanyId(Integer.valueOf(strArr[0]));
            rateVO.setMasterId(Integer.valueOf(strArr[1]));
            rateVO.setServProductGroupId(strArr[2]);
            rateVO.setQuotationRate(MathUtil.round(MathUtil.mul(doubleMeasureResultDO.getValue(), 100), 2));
            quotationRateList.add(rateVO);
        });
        return quotationRateList;
    }

    /**
     * 查询师傅排名
     *
     * @param voList
     * @return
     */
    public List<QuotationRateRankingVO> getRanking(List<QuotationRateVO> voList, Integer masterId) {

        List<QuotationRateRankingVO> rankingList = Lists.newArrayList();
        if (CollectionUtil.isNullOrEmpty(voList)) {
            return rankingList;
        }
        List<Map.Entry<Double, List<QuotationRateVO>>> list = voList.stream()
                .collect(Collectors.groupingBy(QuotationRateVO::getQuotationRate))
                .entrySet()
                .stream()
                .sorted((s1, s2) -> -Double.compare(s1.getKey(), s2.getKey()))
                .collect(Collectors.toList());

        Map<Integer, Integer> rankMap = new HashMap<>();
        for (Map.Entry<Double, List<QuotationRateVO>> entry : list) {
            Optional<QuotationRateVO> first = entry.getValue().stream().filter(e -> e.getMasterId().equals(masterId)).findFirst();
            if (first.isPresent()) {
                QuotationRateVO vo = first.get();
                int rank = Objects.isNull(rankMap.get(vo.getServProductGroupId())) ? 1 : rankMap.get(vo.getServProductGroupId()) + 1;
                QuotationRateRankingVO rankingVO = QuotationRateRankingVO.builder().ranking(rank).quotationRate(vo.getQuotationRate())
                        .servProductGroupId(vo.getServProductGroupId()).servProductGroupName(vo.getServProductGroupName()).build();
                rankingList.add(rankingVO);
                log.info("{} 计价器使用排名为：{} ,使用率为：{},产品组为：{}", vo.getMasterName(), rank, vo.getQuotationRate(), vo.getServProductGroupName());
            }
            List<Map.Entry<Integer, List<QuotationRateVO>>> servProductCollect = new ArrayList(entry.getValue().stream()
                    .collect(Collectors.groupingBy(QuotationRateVO::getServProductGroupId)).entrySet());
            for (Map.Entry<Integer, List<QuotationRateVO>> vo : servProductCollect) {
                rankMap.put(vo.getKey(), vo.getValue().size() + Optional.ofNullable(rankMap.get(vo.getKey())).orElse(0));
            }
        }
        return rankingList;
    }

}
